package com.tanhua.server.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.domain.db.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //记录请求地址
        String requestMethod = request.getMethod();
        log.info("请求了路径:{}:{}", requestMethod, request.getRequestURI());
        //从请求头获取token
        String token = request.getHeader("Authorization");
       //token可能没有值
        if (StringUtils.isNotEmpty(token)) {
            User user = getLoginUserByToken(token);
            if (null != user) {
                //把用户数据存入线程中
                UserHolder.setUser(user);
                log.debug("当前登入用户id为：{}",user.getId());
                return true;
            }
        }

        //如果token没有值则返回状态码401（没有登入或没有权限）
        response.setStatus(401);
        return false;
    }

    /**
     * 通过token获取redis中存入的登录用户信息
     *
     * @param token
     * @return
     */
    private User getLoginUserByToken(String token) {
        //1.1 拼接key,必须与存入时的key要一致
        String key = "TOKEN_" + token;
        //1.2 从redis中取出
        String loginUserJsonString = stringRedisTemplate.opsForValue().get(key);
        //1.3 redis中没有值， 报错，重新登录
        if (StringUtils.isEmpty(loginUserJsonString)) {
            //返回空
            return null;
        }
        //1.4 有值，把json字符串转成java对象User
        return JSON.parseObject(loginUserJsonString, User.class);
    }
}
